//
//  XMLParser.m
//  Alfresco
//
//  Created by Michael Muller on 8/22/09.
//  Copyright 2010 Zia Consulting.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

#import "XMLParser.h"

@implementation XMLParser

@synthesize root;
@synthesize stack;

- (id)initWithContentsOfURL:(NSURL *)url {
	[super initWithContentsOfURL: url];
	stack = [[NSMutableArray alloc] init];
	[self setDelegate:self];
	return self;
}

- (void) dealloc {
	[stack release];
	[root release];  // TODO: figure out why causes access violation
	[super dealloc];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

	XMLNode *node = [[XMLNode alloc] init];
	[node setTagName:elementName];
	[node setAttributes:attributeDict];	
	
	if ([stack count] == 0) {
		[self setRoot:node];
	}
	else {
		[[stack lastObject] addChild:node];
	}
	[stack addObject: node];
	[node release];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	// TODO: verify that the element name matches
	// TODO: verify that there is a node to pop
	
	[stack removeLastObject];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	[[stack lastObject] appendStringToBody:string];
}

@end
